package com.xiaoxin.executor.batch.writer;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.batch.item.adapter.ItemWriterAdapter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.Assert;

import javax.sql.DataSource;
import java.util.List;

/**
 * 用于同步完数据的删除
 *
 * @author ZhangXX
 * @version 0.0.1 Create at 2017-11-09 14:46
 */
public class FinalWriter extends ItemWriterAdapter<Object> implements InitializingBean {

	private static Logger logger = LogManager.getLogger(FinalWriter.class);

	private JdbcTemplate jdbcTemplate;

	private DataSource dataSource;

	private String sql;

	public String getSql() {
		return sql;
	}

	public void setSql(String sql) {
		this.sql = sql;
	}

	public void write(List<? extends Object> items) throws Exception {
		logger.info("Execute SQL:{}", sql);
		jdbcTemplate.batchUpdate(sql);
		logger.info("Final writer execute complete.");
	}

	public void afterPropertiesSet() throws Exception {
		validateAndInit();
		Assert.notNull(dataSource, "dataSource limit must be set");
		Assert.notNull(sql, "sql limit must be set");
	}

	public void validateAndInit() {
		if (StringUtils.isEmpty(sql)) {
			throw new IllegalArgumentException("sql cannot be null");
		}
		if (dataSource != null && jdbcTemplate == null) {
			jdbcTemplate = new JdbcTemplate(dataSource);
		}
		if (jdbcTemplate == null) {
			throw new IllegalArgumentException("jdbcTemplate cannot be null");
		}
	}

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
}
